import axios from 'axios'
import { Message } from '_element-ui@2.13.2@element-ui'
import store from '@/store'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // baseURL: 'http://ihrm-java.itheima.net',
  timeout: 5000 // request timeout
})

// request interceptor   请求拦截器
service.interceptors.request.use(

  config => {
    const token = store.state.user.token
    config.headers.Authorization = `Bearer ${token}`
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor  响应拦截器
service.interceptors.response.use(

  response => {
    if (response.data.success) {
      return response.data
    } else {
      Message({
        type: 'error',
        message: response.data.message,
        duration: 3 * 1000

      })
      return Promise.reject(new Error(response.data.message))
    }
  },

  error => {
    return Promise.reject(error)
  }
)

export default service
